<template>
  <teleport to="body">
    <div 
      class="word-tooltip fixed z-50 pointer-events-auto"
      :style="tooltipStyle"
      @click.stop
    >
      <div class="flex items-start justify-between mb-3">
        <div class="flex-1">
          <h3 class="text-xl font-bold text-text-primary mb-1">{{ word }}</h3>
          <p class="text-sm text-text-secondary">{{ getPinyin(word) }}</p>
        </div>
        <button 
          @click="$emit('close')"
          class="w-6 h-6 rounded-full bg-gray-100 hover:bg-gray-200 flex items-center justify-center text-gray-500 hover:text-gray-700 transition-colors"
        >
          <span class="text-xs">×</span>
        </button>
      </div>
      
      <p class="text-text-secondary leading-relaxed">{{ explanation }}</p>
      
      <!-- 指向箭头 -->
      <div class="absolute -bottom-2 left-1/2 transform -translate-x-1/2">
        <div class="w-0 h-0 border-l-4 border-r-4 border-t-4 border-transparent border-t-white"></div>
      </div>
    </div>
    
    <!-- 背景遮罩 -->
    <div 
      class="fixed inset-0 bg-black bg-opacity-20 z-40"
      @click="$emit('close')"
    ></div>
  </teleport>
</template>

<script setup lang="ts">
import { computed } from 'vue'
import { usePoetryStore } from '@/stores/poetry'

interface Props {
  word: string
  explanation: string
  position: { x: number; y: number }
}

const props = defineProps<Props>()

defineEmits<{
  close: []
}>()

const poetryStore = usePoetryStore()

// 计算气泡样式
const tooltipStyle = computed(() => {
  const padding = 16
  const maxWidth = 280
  
  // 基础位置
  let left = props.position.x - maxWidth / 2
  let top = props.position.y - 200 // 在点击位置上方显示
  
  // 边界检查
  if (left < padding) left = padding
  if (left + maxWidth > window.innerWidth - padding) {
    left = window.innerWidth - maxWidth - padding
  }
  
  if (top < padding) {
    // 如果上方空间不够，显示在下方
    top = props.position.y + 20
  }
  
  return {
    left: `${left}px`,
    top: `${top}px`,
    width: `${maxWidth}px`
  }
})

// 获取词汇拼音（从当前古诗数据中匹配）
const getPinyin = (word: string): string => {
  // 在当前展示的古诗中查找匹配的词汇拼音
  const currentPoetry = poetryStore.poetryCollection?.poems.find(p => 
    p.key_words?.some(w => w.word.includes(word) || word.includes(w.word))
  )
  
  if (currentPoetry) {
    const matchedWord = currentPoetry.key_words?.find(w => 
      w.word.includes(word) || word.includes(w.word)
    )
    if (matchedWord) {
      return matchedWord.pinyin
    }
  }
  
  return '' // 如果没找到，返回空字符串
}
</script>

<style scoped>
.word-tooltip {
  background: white;
  border-radius: 24px;
  box-shadow: 0 24px 48px rgba(45, 55, 72, 0.2);
  padding: 24px;
  max-width: 280px;
  animation: tooltip-appear 400ms cubic-bezier(0.34, 1.56, 0.64, 1);
  border: 1px solid rgba(0, 0, 0, 0.05);
}

@keyframes tooltip-appear {
  0% {
    opacity: 0;
    transform: translateY(20px) scale(0.8);
  }
  100% {
    opacity: 1;
    transform: translateY(0) scale(1);
  }
}
</style>